package com.rent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rent.beans.resp.HouseListResp;
import com.rent.entity.UserHouse;
import com.rent.enums.DeleteEnum;
import com.rent.mapper.UserHouseMapper;
import com.rent.service.UserHouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author
 * @since 2021-06-05
 */
@Service
public class UserHouseServiceImpl extends ServiceImpl<UserHouseMapper, UserHouse> implements UserHouseService {

    @Autowired
    UserHouseMapper userHouseMapper;

    @Override
    public boolean careHouse(Integer userId, Boolean care, Integer houseId) {
        if (care == null) {
            care = true;
        }
        LambdaQueryWrapper<UserHouse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserHouse::getUserId, userId)
                .eq(UserHouse::getHouseId, houseId)
                .eq(UserHouse::getIsDel, DeleteEnum.NO.getCode());
        UserHouse userHouse = getOne(queryWrapper);
        if (userHouse == null && !care) {
            return true;
        }
        if (Objects.nonNull(userHouse)) {
            if (!care) {
                userHouse.setIsDel(DeleteEnum.YES.getCode());
                userHouse.setUpdateTime(new Date());
                this.updateById(userHouse);
                return true;
            }
            return true;
        }
        userHouse = new UserHouse();
        userHouse.setHouseId(houseId);
        userHouse.setUserId(userId);
        return save(userHouse);
    }

    @Override
    public IPage<HouseListResp> findPageByUserId(Page<?> page, Integer userId) {
        return userHouseMapper.selectPageByUserId(page, userId);
    }

    @Override
    public boolean isCareHouse(Integer userId, Integer houseId) {
        LambdaQueryWrapper<UserHouse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(UserHouse::getUserId, userId)
                .eq(UserHouse::getHouseId, houseId)
                .eq(UserHouse::getIsDel, DeleteEnum.NO.getCode());
        int count = count(queryWrapper);
        return count > 0;
    }

    @Override
    public int deleteByHouseId(Integer houseId) {
        return this.userHouseMapper.updateDeleteStatusByHouseId(houseId);
    }
}
